from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection
from decimal import Decimal
from rest_framework.response import Response
from goods.models import SKU
from orders.serializers import PlaceOrderSerialzier,OrderCommitSerializer



class PlaceOrderView(APIView):
    """

    获取订单相关的数据
    1.必须是登录用户才可以访问的
    2.商品列表的数据都是通过redis获取，而且是获取的 选中商品的信息
    3.把运费动态返回给前段

    GET      /orders/places/
    """

    #1.必须是登录用户才可以访问的
    permission_classes = [IsAuthenticated]
    def get(self,request):
        user = request.user
        redis_conn = get_redis_connection('cart')

        redis_id_count = redis_conn.hgetall('cart_%s'%user.id)
        redis_selected_ids = redis_conn.smembers('cart_selected_%s'%user.id)

        selected_data = {}
        for sku_id in redis_selected_ids:
            selected_data[int(sku_id)] = int(redis_id_count[sku_id])

        skus = SKU.objects.filter(pk__in = selected_data.keys())

        for sku in skus:
            sku.count = selected_data[sku.id]

        freight = Decimal('10.00')

        serializer = PlaceOrderSerialzier({'skus':skus,'freight':freight})

        return Response(serializer.data)


from rest_framework.mixins import CreateModelMixin
from rest_framework.generics import CreateAPIView

class OrderView(CreateAPIView):

    permission_classes = [IsAuthenticated]
    serializer_class = OrderCommitSerializer
